package main

import (
	"fmt"
	"io"
	"net"
	"net/http"
	"os"
)

/**
1、接收客户端 request，并将 request 中带的 header 写入 response header
2、读取当前系统的环境变量中的 VERSION 配置，并写入 response header
3、Server 端记录访问日志包括客户端 IP，HTTP 返回码，输出到 server 端的标准输出
4、当访问 localhost/healthz 时，应返回 200
*/
const (
	XForwardedFor = "X-Forwarded-For"
	XRealIP       = "X-Real-IP"
	Version       = "VERSION"
)

func main() {
	os.Setenv(Version, "version1")

	mux := http.NewServeMux()
	mux.HandleFunc("/healthz", healthz)
	http.ListenAndServe(":8080", mux)
}

func healthz(w http.ResponseWriter, req *http.Request) {
	ip := ClientIP(req)
	fmt.Printf("Client[%s] access\n", ip)
	for k, v := range req.Header {
		fmt.Println(k, v)
		for _, h := range v {
			w.Header().Add(k, h)
		}
	}
	version := os.Getenv(Version)
	w.Header().Add(Version, version)
	w.WriteHeader(http.StatusOK)

	io.WriteString(w, "<p>Hello world</p>")
	io.WriteString(w, "IP:"+ip)

}

func ClientIP(req *http.Request) string {
	remoteAddr := req.RemoteAddr
	if ip := req.Header.Get(XRealIP); ip != "" {
		remoteAddr = ip
	} else if ip = req.Header.Get(XForwardedFor); ip != "" {
		remoteAddr = ip
	} else {
		remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
	}

	if remoteAddr == "::1" {
		remoteAddr = "127.0.0.1"
	}

	return remoteAddr
}
